import request from './request'
import {deepCopy} from "@/utils/index";
// import router from "../router/index";
// import store from "@/store";
// import {mapMutations} from "vuex";

export const initMenu = (router, store) => {
  if (store.state.menu.menuList.length > 0) {
    return ;
  }

  //请求后台拿到菜单数据
  request.get('/sys/menu/getMenuByUserId').then( resp => {
    if (resp.data) {
      //格式化的路由
      let routes = JSON.parse(JSON.stringify(resp.data.menus));
      let fmtRoutes = formatRoutes(routes)
      router.addRoutes(fmtRoutes)
      //404需要添加在所有路由的最后面
      router.addRoutes([
        {
          path: '*', redirect: '/404', hidden: true
        }
      ])
      // router.addRoute({
      //   path: '*', redirect: '/404', hidden: true
      // })
      //将数据存入vuex
      store.commit('menu/INIT_ROUTER', fmtRoutes)
      store.commit('menu/SET_AUTHORIZATION', resp.data.auths)

    }
  })
}

export const formatRoutes = (routes) => {
  let fmtRoutes = [];

  routes.forEach( route => {
    if (route.children && route.children instanceof Array) {
      route.children = formatRoutes(route.children)
    }
    //组件不为空
    if (route.component) {

      let router = {
        path: route.path,
        // component : require('@' + route.component + '.vue'),
        component(resolve) {
          require(['@/' + route.component + '.vue'], resolve)
        },
        // component : resolve => require([`@/${com}.vue`], resolve),
        redirect: '', //不需要会怎么样？
        name: route.name,
        meta: {
          title: route.title,
          icon: route.icon,
        },
        hidden: route.hidden,
        children: route.children
      }
      fmtRoutes.push(router)
    }
  })
  return fmtRoutes
}

export const formatAuth = (routes) => {
  let authList = [];
  routes.forEach( route => {
    if (route.children && route.children instanceof Array) {
      route.children = formatAuth(route.children)
    }
    //组件不为空
    if (route.url) {
      authList.push(route.authCode)
    }
  })
  return authList
}

// export const loadView = (view) => {
//   const path = subObliqueLine(view)
//   return (resolve) => require([`@${view}.vue`], resolve)
// }
//
//
// export const importPath = (comUrl) => {
//   const path = subObliqueLine(comUrl)
//   console.log(path)
//   return () => import(`@/${path}.vue`)
// }
// export const subObliqueLine = (str) => {
//   if (str === undefined) {
//     return str
//   }
//   return str.replace(/(^\/*)/g, '')
// }


